import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JFileChooser;

/**
 * TODO DOCUMENT ME!
 *
 * @author dbru
 * @version 0.0
 */
public class HTMLTOPHP {

    /**
     * Creates a new instance of this class.
     *
     */
    public HTMLTOPHP() {
        chooseFiles();
    }

    private void chooseFiles() {
        JFileChooser jfc = new JFileChooser();
        jfc.setMultiSelectionEnabled(true);
        if (jfc.showOpenDialog(jfc) == JFileChooser.APPROVE_OPTION) {
            File[] choosedfiles = jfc.getSelectedFiles();
            processFiles(choosedfiles);
        }
        else {
            System.exit(0);
        }
    }

    private void processFiles(File[] someChoosedfiles) {
        for (int i = 0; i < someChoosedfiles.length; i++) {
            translateFile(someChoosedfiles[i]);
        }
        System.exit(0);
    }

    private void translateFile(File file) {
        String name = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf(".")) + ".php";
        File trFile = new File(name);

        if (!trFile.exists()) {

            try {
                trFile.createNewFile();
                BufferedReader br = new BufferedReader(new FileReader(file));
                BufferedWriter bw = new BufferedWriter(new FileWriter(trFile));
                    
                String line = null;
                bw.write("<?php");
                bw.newLine();
                while((line = br.readLine()) != null){
                    line = line.replaceAll("\"", "'");
                    String phpLine = "echo \"" + line + "\\n\";";
                    bw.write(phpLine);
                    bw.newLine();
                }
                
                bw.write("?>");
                bw.newLine();
                br.close();
                bw.flush();
                bw.close();
            }
            catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                throw new RuntimeException(e);
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                throw new RuntimeException (e);
            }

        }
    }

    /**
     * TODO DOCUMENT ME!
     *
     * @param args
     */
    public static void main(String[] args) {
        new HTMLTOPHP();
    }

}
